package backpropagation;

import java.util.ArrayList;
import java.util.Random;

public class RedNeuronal {

	private ArrayList<SigmoidUnit> hiddenLayer;
	private SigmoidUnit outputLayer;

	RedNeuronal(int cantInput, int cantHidden, int cantOutput) {
		Random rand = new Random();

		hiddenLayer = new ArrayList();

		for (int i = 0; i < cantHidden; i++) {
			hiddenLayer.add(new SigmoidUnit(cantInput, rand));
		}

		if (cantOutput != 1) {
			System.out.println("ERROR: solo se pueden crear redes neuronales con 1 salida");
		}
		outputLayer = new SigmoidUnit(cantHidden, rand);


	}

	private double inversaSigmoid(double x) {
		return -Math.log((1.0 / x) - 1.0);
	}

	private double sigmoid(double x) {
		return 1 / (1 + Math.exp(-x));
	}

	void entrenar(ArrayList<ArrayList<Double>> ejs, ArrayList<Double> salidaEjs, int cant) {
		for (int i = 0; i < cant; i++) {
			for (int j = 0; j < ejs.size(); j++) {
				ArrayList<Double> outputHidden = new ArrayList();
				for (int k = 0; k < hiddenLayer.size(); k++) {
					outputHidden.add(hiddenLayer.get(k).computar(ejs.get(j)));
				}
				double salida = outputLayer.computar(outputHidden);
				ArrayList<Double> pesosOutput = outputLayer.getPesos();
				double error = outputLayer.aprenderOutput(sigmoid(salidaEjs.get(j)));
				
//				double error = outputLayer.aprenderOutput(salidaEjs.get(j));
				for (int k = 0; k < hiddenLayer.size(); k++) {
//					System.out.println(pesosOutput.get(k));
					hiddenLayer.get(k).aprenderHidden(error, pesosOutput.get(k)); // ESTO ESTA MAL!!!!!!!
				}
			}
		}
	}

	double computar(ArrayList<Double> ej) {
		ArrayList<Double> outputHidden = new ArrayList();
		for (int k = 0; k < hiddenLayer.size(); k++) {
			outputHidden.add(hiddenLayer.get(k).computar(ej));
		}
		double salida = outputLayer.computar(outputHidden);
//		return salida;
		return inversaSigmoid(salida);
	}
}
